package com.ljm.security.core;

import com.ljm.security.api.SecurityApi;
import com.ljm.security.dto.SecurityResRule;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: ChenHuaMing
 * @Date: 2020/6/23 11:23
 * @Description:
 */
public class CustomRoleVoter implements AccessDecisionVoter<Object> {
    private SecurityApi securityApi;

    public CustomRoleVoter(SecurityApi securityApi) {
        this.securityApi = securityApi;
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
        if(authentication == null) {
            return ACCESS_DENIED;
        }
        int result = ACCESS_ABSTAIN;
        // 获取当前请求url
        String requestUrl = ((FilterInvocation) object).getHttpRequest().getServletPath();
        //获取权限规则
        SecurityResRule resRule = securityApi.getResRule(requestUrl);
        if(resRule!=null&&!resRule.isFdLoginVisible()){
            Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication);
            result=authorities.stream().anyMatch(auth->auth.getAuthority().equals(requestUrl))?ACCESS_GRANTED:ACCESS_DENIED;
        }
        return result;
    }

    private Collection<? extends GrantedAuthority> extractAuthorities(
            Authentication authentication) {
        return authentication.getAuthorities();
    }
}
